import '../../helper/component/download/controller.dart';
import '../../helper/component/download/state.dart';
import '../../helper/utils/util.dart';
import 'index.dart';
import 'muti_download_2/index.dart';

class MutiDownloadController extends GetxController {
  MutiDownloadController();

  final state = MutiDownloadState();

  void onCell(DownloadFileModel m) {
    Get.to(() => const MutiDownload_2Page(),
            binding: MutiDownload_2Binding(), arguments: m)
        ?.then((value) {
      if (value == 'update') {
        getData();
      }
    });
  }

  void onCellChoose(DownloadFileModel model) {
    if (state.editList.contains(model)) {
      state.editList.remove(model);
    } else {
      state.editList.add(model);
    }

    update(['${model.name}-choose', 'all-choose']);
  }

  void onAllChoose() {
    if (state.list?.isNotEmpty != true) {
      return;
    }
    if (state.editList.length == state.list?.length) {
      state.editList = [];
    } else {
      state.editList.addAll(state.list ?? []);
    }
    update();
  }

  void onAllPause() async {
    await DownloadController.instance.pauseAll();
    update();
  }

  void onAllRemove() async {
    if (state.list?.isNotEmpty != true) {
      return;
    }
    await DownloadController.instance.removeAll();
    Get.back(result: 'update');
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() async {
    super.onReady();
    getData();
  }

  void getData() async {
    state.list = await DownloadController.instance.getAllData();
    update();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
